package com.yanhao.act

import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.webkit.*
import androidx.activity.OnBackPressedCallback
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import com.yanhao.databinding.ActivityWebInfoBinding
import com.yanhao.viewmode.WebFragmentViewModel

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
class WebInfoActivity : AppCompatActivity() {
    companion object {
        val TITLE = "title"
        val LINK = "link"
    }

    // TODO: Rename and change types of parameters
    private var link: String? = null
    private var title: String? = null

    private val rootView by lazy {
        ActivityWebInfoBinding.inflate(layoutInflater)
    }

    //定义回调
    private val callback = object : OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            if (rootView.webview.canGoBack()) {
                //返回上一个h5页面
                rootView.webview.goBack()
            } else {
            }
        }
    }

    private val viewmode: WebFragmentViewModel by viewModels()

    //TODO activity和fragment共享同一个viewmodel
//    private val vm:WebFragmentViewModel by activityViewModels()


    override fun onResume() {
        super.onResume()
    }

    override fun onPause() {
        super.onPause()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(rootView.root)

        link = intent.getStringExtra(LINK)
        title = intent.getStringExtra(TITLE)

        rootView.llBack.setOnClickListener {
            if (rootView.webview.canGoBack()) {
                //返回上一个h5页面
                rootView.webview.goBack()
            } else {
                finish()
            }
        }
        title?.let {
            rootView.tvTitle.text = title
        }
        loadWeb()
    }


    private fun loadWeb() {
        val webSetting: WebSettings = rootView.webview.settings
        webSetting.javaScriptEnabled = true
        rootView.webview.settings.apply {
            layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
            loadWithOverviewMode = true
        }
        //如果不设置webviewclient 请求会跳转系统浏览器
        rootView.webview.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                //返回false，意味着请求过程里，不管有多少次的跳转请求（即新的请求地址）
                //均交给webView自己处理，这也是此方法的默认处理
                return false
            }

            override fun shouldOverrideUrlLoading(
                view: WebView?,
                request: WebResourceRequest?
            ): Boolean {
                //返回false，意味着请求过程里，不管有多少次的跳转请求（即新的请求地址）
                //均交给webView自己处理，这也是此方法的默认处理
                return false
            }
        }
        link?.let { rootView.webview.loadUrl(it) }
        viewmode.maxprogress.observe(this) { process ->
            rootView.progress.setProgress(process)
        }
        viewmode.isVisible.observe(this) { isShow ->
            if (isShow) {
                rootView.progress.visibility = View.GONE
            } else {
                rootView.progress.visibility = View.VISIBLE
            }
        }
        rootView.progress.max = 100
        rootView.webview.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                super.onProgressChanged(view, newProgress)
                if (newProgress < 100) {
                    //进度小于100 显示进度
                    viewmode.progressShow()
                } else if (newProgress == 100) {
                    //进度小于100 隐藏进度
                    viewmode.progressHide()
                }
                viewmode.setProgress(newProgress)
            }
        }

    }

    override fun onBackPressed() {
        if (rootView.webview.canGoBack()) {
            //返回上一个h5页面
            rootView.webview.goBack()
        } else {
            finish()
        }
    }


    override fun onDestroy() {
        rootView.webview?.let {
            (it.getParent() as ViewGroup).removeView(it) //先从父控件中移除 WebView.
            it.stopLoading()
            it.settings.javaScriptEnabled = false
            it.clearHistory()
            it.removeAllViews()
            it.destroy()
        }
        super.onDestroy()
    }
}